package com.lz.demo;

/**
 * @Description: Demo
 * @Date: 2020/5/5 11:24
 * @Author: LiZhen
 * @Version: 1.0
 */
class Food {

    public int count = 1;
    public int maxCount = 20;

    public synchronized void product() {
        while (count >= maxCount) {
            try {
                wait();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        count++;
        try {
            Thread.sleep(25);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.println(Thread.currentThread().getName() + " 生产一个汉堡，当前汉堡数：" + count);
        if (count == maxCount) {
            notifyAll();
        }
    }

    public synchronized void consume() {
        while (count <= 0) {
            try {
                wait();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }

        count--;
        try {
            Thread.sleep(20);
        } catch (Exception e) {
            e.printStackTrace();
        }
        System.out.println(Thread.currentThread().getName() + " 消费一个汉堡，当前汉堡数：" + count);
        if (count == 0) {
            notifyAll();
        }
    }
}

class Producter extends Thread {

    private final Food food;

    public Producter(Food food) {
        super();
        this.food = food;
    }

    @Override
    public void run() {
        while (true) {
            food.product();
        }
    }
}

class Consumer extends Thread {
    private final Food food;

    public Consumer(Food food) {
        super();
        this.food = food;
    }

    @Override
    public void run() {
        while (true) {
            food.consume();
        }
    }
}


public class Demo {
    public static void main(String[] args) {
        Food food = new Food();

        Producter producter1 = new Producter(food);
        Producter producter2 = new Producter(food);
        Consumer consumer1 = new Consumer(food);
        Consumer consumer2 = new Consumer(food);
        producter1.start();
        producter2.start();
        consumer1.start();
        consumer2.start();
    }
}

